package com.hfi.controller;

import com.hfi.mapper.EmployeeMapper;
import com.hfi.model.Employee;
import com.hfi.service.EmployeeService;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2019/5/22
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private SqlSession batchSqlSession;

    /**
     * 在开启二级缓存的情况下 employeeMapper是单例的 所以其会从二级缓存中取到值
     * @param id
     * @return
     */
    @GetMapping("/getEmployeeById")
    @ResponseBody
    public Employee getEmployeeById(@RequestParam Integer id) {
        return employeeService.getEmployeeById(id);
    }

    @GetMapping("/getEmpByLastNameLikeReturnMap")
    @ResponseBody
    public Map<String, Employee> getEmpByLastNameLikeReturnMap(@RequestParam String lastName) {
        return employeeService.getEmpByLastNameLikeReturnMap(lastName);
    }

    @GetMapping("/getEmpByIdByStep")
    @ResponseBody
    public Employee getEmpByIdByStep(@RequestParam Integer id) {
        return employeeService.getEmpByIdByStep(id);
    }

    @PostMapping("/getEmpsByConditionIf")
    @ResponseBody
    public List<Employee> getEmpsByConditionIf(@RequestBody Employee employee) {
        return employeeService.getEmpsByConditionIf(employee);
    }

    /**
     * 这个是使用SimpleExecutor来执行的
     * @param emps
     */
    @PostMapping("addEmps")
    @ResponseBody
    public String addEmps(@RequestBody List<Employee> emps) {
        System.out.println("add emps");
        employeeService.addEmps(emps);
        return "success";
    }

    @PostMapping("addEmpsBatch")
    @ResponseBody
    public String addEmpsBatch(@RequestBody Employee[] emps) {
        EmployeeMapper mapper = batchSqlSession.getMapper(EmployeeMapper.class);
        for (Employee emp : emps) {
            mapper.addEmp(emp);
        }
        batchSqlSession.clearCache();
        return "success";
    }


    @PostMapping("addEmp")
    @ResponseBody
    public Long addEmp(@RequestBody Employee employee) {
        return employeeService.addEmp(employee);
    }
}
